package com.lg.my.netty.chart;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * 简单聊天室的client端
 *
 * @author by Mr. Li 2021/4/22 0:36
 */
public class MyChartClient {
    public static void main(String[] args) throws InterruptedException {

        final NioEventLoopGroup eventExecutors = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            final ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast("decoder", new StringDecoder());

                            pipeline.addLast(new MyChatClientHandler());
                        }
                    });

            // 连接ip 和端口号
            final ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9000).sync();

            // 监听键盘输入
            final Channel channel = channelFuture.channel();
            System.out.println("当前客户端ip：" + channel.remoteAddress());

            final Scanner scanner = new Scanner(System.in);

            while (scanner.hasNextLine()) {
                channel.writeAndFlush(scanner.nextLine());
            }

        } finally {
            eventExecutors.shutdownGracefully();
        }

    }
}
